package com.baidu.controller.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AllFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            //首先进行数据的强制转换,将参数中请求响应类型分别转换成http请求响应类型
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            //首先解除index.jsp,login.jsp,页面登录验证
            //通过资源定位获取虚拟目录的路径
            String uri = request.getRequestURI();
            //根据虚拟路径后缀中包含的信息判断以上的条件的哪些页面应该解除验证
            if (uri.contains("/index.jsp") ||uri.contains("/login.jsp")|| "/stuManager/".equals(uri)||uri.contains("/loginServlet"))
            {
                //如果检测到是以上的界面访问，则放开通道
                filterChain.doFilter(request,response);
                return;
            }
            //判断用户是否是登录的状态
            //获取session域名的的账号
            Object username = request.getSession().getAttribute("username");
            if (username ==null || "".equals(username))
            {
                //如果获取不到用户登录信息则重定向到登录页面
                response.sendRedirect(request.getContextPath()+"/login.jsp");
                return;
            }
            //否则放开通过
            filterChain.doFilter(request,response);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }

    }
}
